package com.chaowen.util;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.Arrays;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import com.chaowen.config.Config;

import android.net.wifi.WifiManager;
import android.os.Handler;

//服务端
public class SignClient implements Runnable{
	private WifiManager.MulticastLock lock;
	private Handler handler;
	private DatagramPacket receive;
	private DatagramSocket server;
	public SignClient(WifiManager manager,Handler handler) {
		this.lock= manager.createMulticastLock("UDPwifi"); 
		this.handler = handler;
	}
	
	private void getClient() throws Exception{
		String[] msgs = getDate();
        System.out.println("Server receive msg:" + msgs[0]+"     "+msgs[1]+"      "+msgs[2]+"      "+msgs[3]);
        if(msgs[0].equals("startSign")) {
        	 Calculate.putData(msgs);
             handler.sendEmptyMessage(100);
        }
        this.lock.release();
        server.close();
	}

	@Override
	public void run() {
		int temp = 0;
		handler.sendEmptyMessage(103);
		while(temp++<5) {
			try {
				getClient();
				Thread.sleep(100);//客户端每个100毫秒进行扫描一次
			} catch(Exception e) {
				e.printStackTrace();
				this.lock.release();
		        server.close();
				handler.sendEmptyMessage(102);
				System.out.println("未找到可用wifi....");
				return;
			}
		}
		handler.sendEmptyMessage(101);
	}
	
	/**
	 * 连接服务器
	 * @throws InterruptedException
	 * @throws ExecutionException
	 * @throws TimeoutException
	 */
	public ExecutorService executor = Executors.newSingleThreadExecutor();
	public String[] getDate() throws Exception {
		Future<String[]> future = executor.submit(new Callable<String[]>(){
			@Override
			public String[] call() throws Exception {
				receive = new DatagramPacket(new byte[1024], 1024);
		        server = new DatagramSocket(Config.signCastPort);
				lock.acquire();
	            server.receive(receive);
	            byte[] recvByte = Arrays.copyOfRange(receive.getData(), 0,
	                    receive.getLength());
	            String msg = new String(recvByte);
	            String msgs[] = msg.split(":");
				return msgs;
			}
		});
		return future.get(6000, TimeUnit.MILLISECONDS);
	}
}